package com.fh.wanandroid.ui.mainpager;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.fh.wanandroid.R;
import com.fh.wanandroid.app.Constants;
import com.fh.wanandroid.base.BaseFragment;
import com.fh.wanandroid.ui.articledetail.ArticleDetailActivity;
import com.fh.wanandroid.ui.mainpager.adaper.ArticleAdaper;
import com.fh.wanandroid.ui.mainpager.adaper.ArticleRvAdapter;
import com.fh.wanandroid.ui.mainpager.bean.BannerData;
import com.fh.wanandroid.ui.mainpager.bean.FeedArticleListData;
import com.fh.wanandroid.utils.GlideImageLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainPagerFragment extends BaseFragment<MainPagerPresenter> implements MainPagerContract.View, OnRefreshListener, OnLoadmoreListener, ArticleRvAdapter.ItemClickListener {

    List<FeedArticleListData.DataBean.DatasBean> articleList;
    @BindView(R.id.main_pager_recycler_view)
    RecyclerView mainPagerRecyclerView;
    @BindView(R.id.srl)
    SmartRefreshLayout srl;
    @BindView(R.id.drawer_layout)
    FrameLayout drawerLayout;


    Banner mBanner;

    ArticleRvAdapter mainPagerRvAdapter;

    ArticleAdaper articleAdaper;

    private List<String> mBannerTitleList;
    private List<String> mBannerUrlList;


    @Override
    public MainPagerPresenter getmPresenter() {
        return new MainPagerPresenter();
    }

    @Override
    public void presenterSetView() {
        if (mPresenter != null) {
            mPresenter.setView(this);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_main_pager;
    }

    @Override
    public void initView() {

        mainPagerRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mainPagerRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        mainPagerRecyclerView.setHasFixedSize(true);
        srl.setOnRefreshListener(this);
        srl.setOnLoadmoreListener(this);


    }

    @Override
    public void initData() {
        articleList = new ArrayList<FeedArticleListData.DataBean.DatasBean>();
        mainPagerRvAdapter = new ArticleRvAdapter(getContext(), articleList);
//        mainPagerRvAdapter.setmItemClickListener(this);
        articleAdaper = new ArticleAdaper(R.layout.item_main_pager,articleList);

        //add head banner
        LinearLayout mHeaderGroup = ((LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.head_banner, null));
        mBanner = mHeaderGroup.findViewById(R.id.head_banner);
        mHeaderGroup.removeView(mBanner);
        articleAdaper.addHeaderView(mBanner);
        mainPagerRecyclerView.setAdapter(articleAdaper);
        mainPagerRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {


                Intent intent = new Intent(getContext(), ArticleDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("id", articleList.get(position).getId());
                bundle.putString("title", articleList.get(position).getTitle());
                bundle.putString("link", articleList.get(position).getLink());
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
//        mainPagerRecyclerView.setAdapter(mainPagerRvAdapter);

    }

    @Override
    public void loadData() {
        srl.autoRefresh();
        mPresenter.getBannerData();
    }


    public static MainPagerFragment getInstance(boolean param1, String param2) {

        MainPagerFragment fragment = new MainPagerFragment();
        Bundle args = new Bundle();
        args.putBoolean(Constants.ARG_PARAM1, param1);
        args.putString(Constants.ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void refreshArticle(FeedArticleListData articleBean) {

        articleList.clear();

        this.articleList.addAll(articleBean.getData().getDatas());

        mainPagerRvAdapter.notifyDataSetChanged();

        finishRefresh();

    }

    @Override
    public void appendArticle(FeedArticleListData articleBean) {

        int oldNum = this.articleList.size();

        this.articleList.addAll(articleBean.getData().getDatas());

        mainPagerRvAdapter.notifyItemRangeChanged(oldNum, this.articleList.size());

        finishLoadMore();

    }

    @Override
    public void getBanner(BannerData bannerData) {

        mBannerTitleList = new ArrayList<>();
        List<String> bannerImageList = new ArrayList<>();
        mBannerUrlList = new ArrayList<>();
        for (BannerData.DataBean dataBean : bannerData.getData() ) {
            mBannerTitleList.add(dataBean.getTitle());
            bannerImageList.add(dataBean.getImagePath());
            mBannerUrlList.add(dataBean.getUrl());
        }
        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
        //设置图片加载器
        mBanner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        mBanner.setImages(bannerImageList);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.DepthPage);
        //设置标题集合（当banner样式有显示title时）
        mBanner.setBannerTitles(mBannerTitleList);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置轮播时间
        mBanner.setDelayTime(bannerData.getData().size() * 400);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);

//        mBanner.setOnBannerListener(i -> JudgeUtils.startArticleDetailActivity(_mActivity, null,
//                0, mBannerTitleList.get(i), mBannerUrlList.get(i),
//                false, false, true));
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();

    }

    @Override
    public void loadDataFail(String msg) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        mPresenter.loadInitData();


    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mPresenter.loadMoreData();
    }

    /**
     * 结束刷新动作
     *
     * @return 是否结束刷新动作
     */
    private boolean finishRefresh() {
        if (srl.isRefreshing()) {
            srl.finishRefresh();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 结束加载更多动作
     */
    private void finishLoadMore() {
        if (srl.isLoading()) {
            srl.finishLoadmore();
        }
    }

    @Override
    public void onClick(int position) {

//        Intent intent = new Intent(getContext(), ArticleDetailActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putInt("id", articleList.get(position).getId());
//        bundle.putString("title", articleList.get(position).getTitle());
//        bundle.putString("link", articleList.get(position).getLink());
//        intent.putExtras(bundle);
//        startActivity(intent);

    }


    public void jumpToTheTop() {
        if (mainPagerRecyclerView != null) {
            mainPagerRecyclerView.smoothScrollToPosition(0);
        }
    }
}
